<?php
// Made by RockerMONO (Nick)
// thanks a ton to danopia for loops and other adjustments to the code!!

if(command("brainfuck")){
  $textToSend="";
  $brainfuck=Array();
  $bfPointer=0;
  $bfSize=30000;
  $eLoop=0;
  for($i=0;$i<$bfSize;$i++){
    $brainfuck[$i]=0;
  }
  for($i=0;$i<strlen($param);$i++){
    if($eLoop>10000){
      SendCommand("PRIVMSG $channel :$sender: Error, endless loop found in program!");
      $textToSend="";
      break;
    }
    $eLoop++;
    $bfItem=$param[$i];
    switch($bfItem){
      case '+':
        if ($brainfuck[$bfPointer] < 255) {
          $brainfuck[$bfPointer]++;
        } else {
          $brainfuck[$bfPointer] = 0;
        }
        break;
      case '-':
        if ($brainfuck[$bfPointer] > 0) {
          $brainfuck[$bfPointer]--;
        } else {
          $brainfuck[$bfPointer] = 255;
        }
        break;
      case '[':
        if ($brainfuck[$bfPointer] == 0)
        {
          $loopDepth = 0;
          for($j=$i+1;$j<strlen($param);$j++)
          {
            if ($param[$j]==']') {
              if ($loopDepth == 0) {
                $i = $j;
                break;
              }else{
                $loopDepth--;
              }
            } else if ($param[$j]=='[') {
                $loopDepth++;
            }
          }
        }
        break;
      case ']':
        if ($brainfuck[$bfPointer] != 0)
        {
          $loopDepth = 0;
          for($j=$i-1;$j>=0;$j--)
          {
            if ($param[$j]=='[') {
              if ($loopDepth == 0) {
                $i = $j;
                break;
              }else{
                $loopDepth--;
              }
            } else if ($param[$j]==']') {
                $loopDepth++;
            }
          }
        }
        break;
      case '.':
        $textToSend.=chr($brainfuck[$bfPointer]);
        break;
      case ',':
        SendCommand("PRIVMSG $channel :$sender: Error, input can not be used!");
        $textToSend="";
        break;
      case '>':
        if($bfPointer>$bfSize){
          SendCommand("PRIVMSG $channel :$sender: Error, no more allocated memory!");
          $textToSend="";
          break;
        }
        $bfPointer++;
        break;
      case '<':
        if ($bfPointer > 0) {
          $bfPointer--;
        }
        break;
    }
  }
  $textToSend=str_replace(chr(0),"[0x00]",$textToSend);
  $textToSend=str_replace(chr(7),"[0x07]",$textToSend);
  $textToSend=str_replace(chr(13),"[0x13]",$textToSend);
  $textToSend=str_replace(chr(10),"[0x10]",$textToSend);
  if(!empty($textToSend)){
    SendCommand("PRIVMSG $channel :$sender: $textToSend");
  }
}
?>